//
//  ViewController.m
//  test
//
//  Created by sss on 2019/7/2.
//  Copyright © 2019年 kb210. All rights reserved.
//

#import "ViewController.h"
#import <GPUImage/GPUImage.h>
#import <GPUImageView.h>

#import <FCUUID.h>

#import <objc/runtime.h>

@interface ViewController ()<GPUImageVideoCameraDelegate,UIPopoverControllerDelegate>
@property(nonatomic,strong) UIImageView *imageV;
@property(nonatomic,strong) AVCaptureDevice *device;// 设备
@property(nonatomic,strong) AVCaptureDeviceInput *input;// 输入
@property(nonatomic,strong) AVCaptureStillImageOutput *output;// 输出

@property(nonatomic,strong) AVCaptureSession *session;// session 输入输出连接管
@property(nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;// 预览层

@property(nonatomic,copy) UIImage *image;

//@property(nonatomic,strong) Reachability *connetion;

// GPUImage
@property(nonatomic,strong) GPUImageStillCamera *gpucamara;

@property(nonatomic,strong) GPUImageFilter *filtter;

@property(nonatomic,strong) GPUImageView  *gpuPreView;


// GPUImageVideo
@property(nonatomic,strong) GPUImageVideoCamera *videoCamara;

@property(nonatomic,strong) NSMutableArray *paths;
@end

@implementation ViewController
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ){
            return device;
        }
    
    return nil;
}
-(void)initVideoCamara{
    self.videoCamara=[[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPresetHigh cameraPosition:AVCaptureDevicePositionBack];
    self.videoCamara.outputImageOrientation=UIInterfaceOrientationPortrait;
    self.filtter=[[GPUImageSketchFilter alloc] init];
    [self.videoCamara addTarget:self.filtter];
    self.gpuPreView=[[GPUImageView alloc] initWithFrame:self.view.bounds];
    self.gpuPreView.fillMode=kGPUImageFillModePreserveAspectRatioAndFill;
    
    [self.filtter addTarget:self.gpuPreView];
    [self.view addSubview:self.gpuPreView];
    self.videoCamara.delegate=self;
    [self.videoCamara startCameraCapture];
}
-(void)initcamara{
    
    self.device=[self cameraWithPosition:AVCaptureDevicePositionBack];
    self.input=[[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    self.output=[[AVCaptureStillImageOutput alloc] init];
    self.session=[[AVCaptureSession alloc] init];
    self.session.sessionPreset=AVCaptureSessionPresetMedium;
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    self.previewLayer=[[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame=self.view.bounds;
    self.previewLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    [self.session startRunning];
    if ([self.device lockForConfiguration:nil]) {
        if([self.device isFlashModeSupported:AVCaptureFlashModeAuto]){
            [self.device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡
        if ([self.device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [self.device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [self.device unlockForConfiguration];
    }
}
-(void)initGPUCamara{
    self.gpucamara=[[GPUImageStillCamera alloc] initWithSessionPreset:AVCaptureSessionPresetHigh cameraPosition:AVCaptureDevicePositionBack];
    self.gpucamara.outputImageOrientation=UIInterfaceOrientationPortrait;
    self.filtter=[[GPUImageSketchFilter alloc] init];
    [self.gpucamara addTarget:self.filtter];
    self.gpuPreView=[[GPUImageView alloc] initWithFrame:self.view.bounds];
    self.gpuPreView.fillMode=kGPUImageFillModePreserveAspectRatioAndFill;
    
    [self.filtter addTarget:self.gpuPreView];
    [self.view addSubview:self.gpuPreView];
    [self.gpucamara startCameraCapture];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(13, 50, 200, 130)];
    view.backgroundColor=[UIColor redColor];
    [self.view addSubview:view];
//    NSLog(@"2");
    UIButton *btn1=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setTitle:@"拍照" forState:UIControlStateNormal];
    [self.view addSubview:btn1];
    btn1.backgroundColor=[UIColor grayColor];
    btn1.frame=CGRectMake(165, 600, 60 , 60);
    //    btn.layer.cornerRadius=30;
    //    btn.layer.borderWidth=5;
    //    btn.layer.borderColor=[UIColor whiteColor].CGColor;
    
    [btn1 addTarget:self action:@selector(btnclcik:) forControlEvents:UIControlEventTouchUpInside];
    

    
   
    
    NSLog(@"%@",[[UIDevice currentDevice] identifierForVendor]);
    
    // 监听网络状态改变的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
//
//    // 创建Reachability
//    Reachability *network = [Reachability reachabilityForInternetConnection];
//    // 开始监控网络(一旦网络状态发生改变, 就会发出通知kReachabilityChangedNotification)
//    [self.connetion startNotifier];
    return;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ntf) name:UIApplicationDidFinishLaunchingNotification object:nil];
    UIImageView *imageView1 = [[UIImageView alloc] init];
    imageView1.frame = self.view.bounds;
    self.imageV=imageView1;
//    [self.view addSubview:imageView1];
//    GPUImageSketchFilter *filtter=[[GPUImageSketchFilter alloc] init];
//    [filtter forceProcessingAtSize:image.size];
//    [filtter useNextFrameForImageCapture];
//    //获取数据源
//    GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:image];
//    //添加上滤镜
//    [stillImageSource addTarget:filtter];
//    //开始渲染
//    [stillImageSource processImage];
//    //获取渲染后的图片
//    UIImage *newImage = [filtter imageFromCurrentFramebuffer];
//    //加载出来
//    UIImageView *imageView = [[UIImageView alloc] initWithImage:newImage];
//
//    imageView.frame = CGRectMake(0,300,375 ,250);
//    [self.view addSubview:imageView];
//    [self initcamara];
//    [self initGPUCamara];
    [self initVideoCamara];
    
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"拍照" forState:UIControlStateNormal];
    [self.view addSubview:btn];
    btn.backgroundColor=[UIColor grayColor];
    btn.frame=CGRectMake(165, 600, 60 , 60);
//    btn.layer.cornerRadius=30;
//    btn.layer.borderWidth=5;
//    btn.layer.borderColor=[UIColor whiteColor].CGColor;
    
    [btn addTarget:self action:@selector(btnclcik:) forControlEvents:UIControlEventTouchUpInside];
    self.paths=[NSMutableArray array];
    CAShapeLayer *shape=[CAShapeLayer layer];
    shape.strokeColor=[UIColor redColor].CGColor;
    shape.fillColor=[UIColor clearColor].CGColor;
    shape.frame=CGRectMake(0, 0, 60, 60);
    shape.lineWidth=10;
    shape.lineJoin=kCALineJoinMiter;
    

    UIBezierPath *path1=[UIBezierPath bezierPathWithArcCenter:CGPointMake(30, 30) radius:30 startAngle:0 endAngle:M_PI*2/5.0 clockwise:YES];
  
   
    
//   [path1 addArcWithCenter:CGPointMake(30, 30) radius:30 startAngle:(M_PI*2/5.0+M_PI*2/360.0*5) endAngle:(M_PI*2/2.5) clockwise:YES];
    

    shape.path=path1.CGPath;
  
    [btn.layer addSublayer:shape];
    
    
}
-(void)ntf{
    NSLog(@"1");
}
-(void)item1click{
    NSLog(@"======item1====");
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UIPopoverPresentationControllerDelegate
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}
-(void)btnclcik:(UIButton*)sender{
    
//    UIViewController *vc=[[UIViewController alloc] init];
//    UIView *red=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
//    red.backgroundColor=[UIColor redColor];
//    [vc.view addSubview:red];
//    vc.view.backgroundColor = [UIColor orangeColor];
//    vc.preferredContentSize = CGSizeMake(150, 150);
//
//    vc.modalPresentationStyle = UIModalPresentationPopover;
//
//    UIPopoverPresentationController *popoverPresentationController = vc.popoverPresentationController;
//    popoverPresentationController.barButtonItem = item;
//    popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
//    popoverPresentationController.delegate = self;
//    [self presentViewController:vc animated:YES completion:nil];
    UIViewController *_vc=[[UIViewController alloc] init];
    _vc.preferredContentSize = CGSizeMake(150, 150);
    _vc.modalPresentationStyle = UIModalPresentationPopover;
    
  
    
    UIButton *item1=[[UIButton alloc] initWithFrame:CGRectMake(0, 20, 150, 80)];
    [item1 addTarget:self action:@selector(item1click) forControlEvents:UIControlEventTouchUpInside];
    [item1 setTitle:@"选项一" forState:UIControlStateNormal];
    item1.backgroundColor=[UIColor blackColor];
    [_vc.view addSubview:item1];
    UIPopoverPresentationController *popoverPresentationController = _vc.popoverPresentationController;
    
    popoverPresentationController.sourceView = sender;
    popoverPresentationController.sourceRect = CGRectMake(sender.frame.size.width / 2, 0, 0, 0);
    popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionDown;
    popoverPresentationController.delegate = (id)self;
    popoverPresentationController.backgroundColor = [UIColor purpleColor];
    
    [self presentViewController:_vc animated:YES completion:nil];
//    CAShapeLayer *shape=[CAShapeLayer layer];
//    shape.strokeColor=[UIColor greenColor].CGColor;
//    shape.fillColor=[UIColor clearColor].CGColor;
//    shape.frame=CGRectMake(0, 0, 60, 60);
//    shape.lineWidth=10;
//    shape.lineJoin=kCALineJoinMiter;
//
//
//    UIBezierPath *path1=[UIBezierPath bezierPathWithArcCenter:CGPointMake(30, 30) radius:30 startAngle:M_PI*2/5.0 endAngle:M_PI*2/2.5 clockwise:YES];
//
//    CAShapeLayer *white=[CAShapeLayer layer];
//    white.strokeColor=[UIColor blueColor].CGColor;
//    white.fillColor=[UIColor clearColor].CGColor;
//    white.frame=CGRectMake(0, 0, 60, 60);
//    white.lineWidth=10;
//    white.lineJoin=kCALineJoinMiter;
//
//
//    UIBezierPath *whitepath=[UIBezierPath bezierPathWithArcCenter:CGPointMake(30, 30) radius:30 startAngle:M_PI*2/5.0 endAngle:(M_PI*2/5.0+M_PI*2/360.0*5) clockwise:YES];
//
//    //   [path1 addArcWithCenter:CGPointMake(30, 30) radius:30 startAngle:(M_PI*2/5.0+M_PI*2/360.0*5) endAngle:(M_PI*2/2.5) clockwise:YES];
//    white.path=whitepath.CGPath;
//    [shape addSublayer:white];
//
//    shape.path=path1.CGPath;
//
//    [sender.layer addSublayer:shape];
    
    
    
    
//    [self.gpucamara capturePhotoAsPNGProcessedUpToFilter:self.filtter withOrientation:(UIImageOrientationUp) withCompletionHandler:^(NSData *processedPNG, NSError *error) {
//        UIImage *image=[UIImage imageWithData:processedPNG];
//        UIImageView *imgv=[[UIImageView alloc] initWithFrame:self.view.bounds];
//        imgv.image=image;
//        [self.view addSubview:imgv];
//        [self.gpucamara stopCameraCapture];
//    }];
}

- (void)photoBtnDidClick
{
    AVCaptureConnection *conntion = [self.output connectionWithMediaType:AVMediaTypeVideo];
    if (!conntion) {
        NSLog(@"拍照失败!");
        return;
    }
    [self.output captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == nil) {
            return ;
        }
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.image = [UIImage imageWithData:imageData];
        [self.session stopRunning];
        self.imageV.image=self.image;
        [self.view addSubview:self.imageV];
    }] ;
     
}

#pragma mark GPUImageVdieoDelegate

-(void)willOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer{
    
//    NSLog(@"----视频流s输出----");
    
}
@end
